<template>
  <div class="admin-page">
    <div class="container">
      <div class="header">
        <h1>页面自定义管理</h1>
        <div class="actions">
          <button class="btn btn-secondary" @click="handleReset">重置所有配置</button>
          <button class="btn btn-primary" @click="handleSave">保存配置</button>
          <button class="btn btn-default" @click="handleBack">返回首页</button>
        </div>
      </div>

      <div class="content">
        <!-- 标题配置 -->
        <div class="section">
          <h2>页面标题配置</h2>
          <div class="form-item">
            <label>自定义标题：</label>
            <input
              v-model="customTitle"
              type="text"
              placeholder="请输入页面标题"
              class="title-input"
            />
          </div>
        </div>

        <!-- Banner配置 -->
        <div class="section">
          <h2>Banner图片配置</h2>
          <div class="banner-config">
            <div class="form-item">
              <label>上传Banner：</label>
              <div class="upload-container">
                <input
                  type="file"
                  ref="fileInput"
                  accept="image/*"
                  @change="handleFileChange"
                  class="file-input"
                />
                <div
                  class="drop-zone"
                  @drop="handleFileDrop"
                  @dragover="handleFileDragOver"
                  @dragenter="handleFileDragEnter"
                  @dragleave="handleFileDragLeave"
                  :class="{ 'drag-over': isDragOver }"
                >
                  <div class="drop-content">
                    <p>拖拽图片到此处或</p>
                    <button class="btn btn-upload" @click="triggerFileSelect">选择图片</button>
                  </div>
                </div>
                <button v-if="customBanner" class="btn btn-clear" @click="clearBanner">
                  清除图片
                </button>
              </div>
            </div>
            <div class="banner-preview" v-if="customBanner">
              <label>预览效果：</label>
              <div class="preview-container">
                <img :src="customBanner" alt="Banner预览" class="preview-image" />
              </div>
            </div>
            <div class="banner-tips">
              <p>
                提示：建议使用656x300像素的图片，支持JPG、PNG、GIF格式，图片将自动转换为BASE64存储
              </p>
            </div>
          </div>
        </div>

        <!-- 二维码图片配置 -->
        <div class="section">
          <h2>二维码图片配置</h2>
          <div class="qrcode-config">
            <div class="form-item">
              <label>上传二维码：</label>
              <div class="upload-container">
                <input
                  type="file"
                  ref="qrcodeFileInput"
                  accept="image/*"
                  @change="handleQrcodeFileChange"
                  class="file-input"
                />
                <div
                  class="drop-zone"
                  @drop="handleQrcodeFileDrop"
                  @dragover="handleFileDragOver"
                  @dragenter="handleFileDragEnter"
                  @dragleave="handleFileDragLeave"
                  :class="{ 'drag-over': isDragOver }"
                >
                  <div class="drop-content">
                    <p>拖拽二维码图片到此处或</p>
                    <button class="btn btn-upload" @click="triggerQrcodeFileSelect">
                      选择图片
                    </button>
                  </div>
                </div>
                <button v-if="customQrcode" class="btn btn-clear" @click="clearQrcode">
                  清除图片
                </button>
              </div>
            </div>
            <div class="qrcode-preview" v-if="customQrcode">
              <label>预览效果：</label>
              <div class="preview-container">
                <img :src="customQrcode" alt="二维码预览" class="preview-qrcode" />
              </div>
            </div>
            <div class="qrcode-tips">
              <p>
                提示：建议使用正方形的二维码图片，支持JPG、PNG、GIF格式，图片将自动转换为BASE64存储
              </p>
            </div>
          </div>
        </div>

        <!-- 服务菜单顺序配置 -->
        <div class="section">
          <h2>服务菜单顺序配置</h2>
          <div class="sort-container">
            <div class="sort-list">
              <div
                v-for="(service, index) in servicesList"
                :key="service.id"
                class="sort-item"
                draggable="true"
                @dragstart="handleDragStart($event, index, 'service')"
                @dragover="handleDragOver"
                @drop="handleDrop($event, index, 'service')"
              >
                <div class="drag-handle">⋮⋮</div>
                <div class="item-content">
                  <img
                    v-if="service.homeImage"
                    :src="handleProxy(service.homeImage)"
                    :alt="service.name"
                    class="item-image"
                  />
                  <span class="item-name">{{ service.name || `服务 ${service.id}` }}</span>
                </div>
                <div class="item-order">{{ index + 1 }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 点位分类顺序配置 -->
        <div class="section">
          <h2>点位分类顺序配置</h2>
          <div class="sort-container">
            <div class="sort-list">
              <div
                v-for="(category, index) in categoriesList"
                :key="category.id"
                class="sort-item"
                draggable="true"
                @dragstart="handleDragStart($event, index, 'category')"
                @dragover="handleDragOver"
                @drop="handleDrop($event, index, 'category')"
              >
                <div class="drag-handle">⋮⋮</div>
                <div class="item-content">
                  <img
                    v-if="category.homeImage"
                    :src="handleProxy(category.homeImage)"
                    :alt="category.name"
                    class="item-image"
                  />
                  <span class="item-name">{{ category.name || `分类 ${category.id}` }}</span>
                </div>
                <div class="item-order">{{ index + 1 }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 提示消息 -->
    <div v-if="message" :class="['message', messageType]">
      {{ message }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getCategoryList, getTopMenu, handleProxy } from '@/api/data.js'
import {
  getCustomTitle,
  setCustomTitle,
  getCustomBanner,
  setCustomBanner,
  getCustomQrcode,
  setCustomQrcode,
  getCustomServiceOrder,
  setCustomServiceOrder,
  getCustomCategoryOrder,
  setCustomCategoryOrder,
  clearAllCustomConfig,
  resetOutdatedConfig,
  updateDataVersion,
} from '@/utils/customStorage.js'

const router = useRouter()

// 响应式数据
const customTitle = ref('')
const customBanner = ref('')
const customQrcode = ref('')
const servicesList = ref([])
const categoriesList = ref([])
const originalServices = ref([])
const originalCategories = ref([])
const message = ref('')
const messageType = ref('success')

// 拖拽相关
const draggedIndex = ref(-1)
const draggedType = ref('')

// 文件上传相关
const fileInput = ref(null)
const qrcodeFileInput = ref(null)
const isDragOver = ref(false)

// 获取数据
const fetchData = async () => {
  try {
    // 获取服务菜单
    const servicesRes = await getTopMenu()
    if (servicesRes.data.code === 200) {
      originalServices.value = servicesRes.data.data
      servicesList.value = getCustomServiceOrder(originalServices.value)
    }

    // 获取分类
    const categoriesRes = await getCategoryList()
    if (categoriesRes.data.code === 200) {
      originalCategories.value = categoriesRes.data.data
      categoriesList.value = getCustomCategoryOrder(originalCategories.value)
    }

    // 检查数据更新并重置过期配置
    resetOutdatedConfig(originalServices.value, originalCategories.value)

    // 获取自定义标题
    customTitle.value = getCustomTitle()

    // 获取自定义Banner
    customBanner.value = getCustomBanner()

    // 获取自定义二维码
    customQrcode.value = getCustomQrcode()
  } catch (error) {
    console.error('获取数据失败:', error)
    showMessage('获取数据失败，请刷新页面重试', 'error')
  }
}

// 拖拽开始
const handleDragStart = (event, index, type) => {
  draggedIndex.value = index
  draggedType.value = type
  event.dataTransfer.effectAllowed = 'move'
}

// 拖拽悬停
const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

// 拖拽放置
const handleDrop = (event, dropIndex, type) => {
  event.preventDefault()

  if (draggedType.value !== type || draggedIndex.value === dropIndex) {
    return
  }

  const list = type === 'service' ? servicesList.value : categoriesList.value
  const draggedItem = list[draggedIndex.value]

  // 移除拖拽的项目
  list.splice(draggedIndex.value, 1)

  // 插入到新位置
  const newIndex = draggedIndex.value < dropIndex ? dropIndex - 1 : dropIndex
  list.splice(newIndex, 0, draggedItem)

  // 重置拖拽状态
  draggedIndex.value = -1
  draggedType.value = ''
}

// 显示消息
const showMessage = (text, type = 'success') => {
  message.value = text
  messageType.value = type
  setTimeout(() => {
    message.value = ''
  }, 3000)
}

// 触发文件选择
const triggerFileSelect = () => {
  fileInput.value?.click()
}

// 触发二维码文件选择
const triggerQrcodeFileSelect = () => {
  qrcodeFileInput.value?.click()
}

// 处理文件选择
const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (!file) return
  processFile(file, 'banner')
}

// 处理二维码文件选择
const handleQrcodeFileChange = (event) => {
  const file = event.target.files[0]
  if (!file) return
  processFile(file, 'qrcode')
}

// 处理文件（通用函数）
const processFile = (file, type = 'banner') => {
  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    showMessage('请选择图片文件！', 'error')
    return
  }

  // 检查文件大小（限制为5MB）
  if (file.size > 5 * 1024 * 1024) {
    showMessage('图片文件大小不能超过5MB！', 'error')
    return
  }

  // 转换为BASE64
  const reader = new FileReader()
  reader.onload = (e) => {
    if (type === 'banner') {
      customBanner.value = e.target.result
      showMessage('Banner图片上传成功！', 'success')
    } else if (type === 'qrcode') {
      customQrcode.value = e.target.result
      showMessage('二维码图片上传成功！', 'success')
    }
  }
  reader.onerror = () => {
    showMessage('图片读取失败，请重试！', 'error')
  }
  reader.readAsDataURL(file)
}

// 拖拽事件处理
const handleFileDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'copy'
}

const handleFileDragEnter = (event) => {
  event.preventDefault()
  isDragOver.value = true
}

const handleFileDragLeave = (event) => {
  event.preventDefault()
  isDragOver.value = false
}

const handleFileDrop = (event) => {
  event.preventDefault()
  isDragOver.value = false

  const files = event.dataTransfer.files
  if (files.length > 0) {
    processFile(files[0], 'banner')
  }
}

// 处理二维码拖拽放置
const handleQrcodeFileDrop = (event) => {
  event.preventDefault()
  isDragOver.value = false

  const files = event.dataTransfer.files
  if (files.length > 0) {
    processFile(files[0], 'qrcode')
  }
}

// 清除Banner
const clearBanner = () => {
  customBanner.value = ''
  if (fileInput.value) {
    fileInput.value.value = ''
  }
  showMessage('Banner已清除', 'success')
}

// 清除二维码
const clearQrcode = () => {
  customQrcode.value = ''
  if (qrcodeFileInput.value) {
    qrcodeFileInput.value.value = ''
  }
  showMessage('二维码已清除', 'success')
}

// 保存配置
const handleSave = () => {
  try {
    // 保存标题
    setCustomTitle(customTitle.value)

    // 保存Banner
    setCustomBanner(customBanner.value)

    // 保存二维码
    setCustomQrcode(customQrcode.value)

    // 保存服务菜单顺序
    const serviceIds = servicesList.value.map((s) => s.id)
    setCustomServiceOrder(serviceIds)

    // 保存分类顺序
    const categoryIds = categoriesList.value.map((c) => c.id)
    setCustomCategoryOrder(categoryIds)

    // 更新数据版本
    updateDataVersion(originalServices.value, originalCategories.value)

    showMessage('配置保存成功！', 'success')
  } catch (error) {
    console.error('保存配置失败:', error)
    showMessage('保存配置失败，请重试', 'error')
  }
}

// 重置配置
const handleReset = () => {
  if (confirm('确定要重置所有自定义配置吗？此操作不可撤销。')) {
    clearAllCustomConfig()

    // 重置页面数据
    customTitle.value = '椒江区人才社区地图'
    customBanner.value = ''
    customQrcode.value = ''
    servicesList.value = [...originalServices.value]
    categoriesList.value = [...originalCategories.value]

    showMessage('配置已重置', 'success')
  }
}

// 返回首页
const handleBack = () => {
  router.push('/index')
}

// 页面加载
onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.admin-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20px;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .header {
    background: linear-gradient(90deg, #44d4a8 33%, #28c68e 100%);
    color: white;
    padding: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h1 {
      margin: 0;
      font-size: 28px;
      font-weight: 600;
    }

    .actions {
      display: flex;
      gap: 12px;
    }

    .btn {
      padding: 10px 20px;
      border: none;
      border-radius: 6px;
      font-size: 14px;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s ease;

      &.btn-primary {
        background: #4caf50;
        color: white;

        &:hover {
          background: #45a049;
        }
      }

      &.btn-secondary {
        background: #ff6b6b;
        color: white;

        &:hover {
          background: #ee5253;
        }
      }

      &.btn-default {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        border: 1px solid rgba(255, 255, 255, 0.3);

        &:hover {
          background: rgba(255, 255, 255, 0.3);
        }
      }
    }
  }

  .content {
    padding: 24px;
  }

  .section {
    margin-bottom: 40px;

    h2 {
      color: #2c3e50;
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #e9ecef;
    }
  }

  .form-item {
    display: flex;
    align-items: center;
    gap: 12px;

    label {
      font-weight: 500;
      color: #495057;
      min-width: 100px;
    }

    .title-input {
      flex: 1;
      max-width: 400px;
      padding: 12px 16px;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      font-size: 14px;
      transition: border-color 0.3s ease;

      &:focus {
        outline: none;
        border-color: #667eea;
      }
    }
  }

  .banner-config {
    .upload-container {
      display: flex;
      flex-direction: column;
      gap: 16px;

      .file-input {
        display: none;
      }

      .drop-zone {
        border: 2px dashed #d1d5db;
        border-radius: 8px;
        padding: 40px 20px;
        text-align: center;
        background: #f9fafb;
        transition: all 0.3s ease;
        cursor: pointer;

        &:hover,
        &.drag-over {
          border-color: #44d4a8;
          background: #f0fdfa;
        }

        .drop-content {
          .drop-icon {
            font-size: 48px;
            margin-bottom: 16px;
          }

          p {
            margin: 0 0 16px 0;
            color: #6b7280;
            font-size: 14px;
          }

          .btn-upload {
            background: linear-gradient(90deg, #44d4a8 33%, #28c68e 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: linear-gradient(90deg, #3bc79e 33%, #24b182 100%);
              transform: translateY(-1px);
            }
          }
        }
      }

      .btn-clear {
        align-self: flex-start;
        background: #ff6b6b;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background: #ee5253;
          transform: translateY(-1px);
        }
      }
    }

    .banner-preview {
      margin-top: 16px;
      display: flex;
      align-items: flex-start;
      gap: 12px;

      .preview-container {
        flex: 1;
        max-width: 500px;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        overflow: hidden;
        background: #f8f9fa;

        .preview-image {
          width: 100%;
          height: auto;
          max-height: 200px;
          object-fit: cover;
          display: block;
        }
      }
    }

    .banner-tips {
      margin-top: 12px;
      padding: 12px;
      background: #e3f2fd;
      border-radius: 6px;
      border-left: 4px solid #2196f3;

      p {
        margin: 0;
        color: #1565c0;
        font-size: 13px;
      }
    }
  }

  .qrcode-config {
    .upload-container {
      display: flex;
      flex-direction: column;
      gap: 16px;

      .file-input {
        display: none;
      }

      .drop-zone {
        border: 2px dashed #d1d5db;
        border-radius: 8px;
        padding: 40px 20px;
        text-align: center;
        background: #f9fafb;
        transition: all 0.3s ease;
        cursor: pointer;

        &:hover,
        &.drag-over {
          border-color: #44d4a8;
          background: #f0fdfa;
        }

        .drop-content {
          .drop-icon {
            font-size: 48px;
            margin-bottom: 16px;
          }

          p {
            margin: 0 0 16px 0;
            color: #6b7280;
            font-size: 14px;
          }

          .btn-upload {
            background: linear-gradient(90deg, #44d4a8 33%, #28c68e 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: linear-gradient(90deg, #3bc79e 33%, #24b182 100%);
              transform: translateY(-1px);
            }
          }
        }
      }

      .btn-clear {
        align-self: flex-start;
        background: #ff6b6b;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          background: #ee5253;
          transform: translateY(-1px);
        }
      }
    }

    .qrcode-preview {
      margin-top: 16px;
      display: flex;
      align-items: flex-start;
      gap: 12px;

      .preview-container {
        flex: 1;
        max-width: 200px;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        overflow: hidden;
        background: #f8f9fa;

        .preview-qrcode {
          width: 100%;
          height: auto;
          max-height: 200px;
          object-fit: contain;
          display: block;
        }
      }
    }

    .qrcode-tips {
      margin-top: 12px;
      padding: 12px;
      background: #e8f5e8;
      border-radius: 6px;
      border-left: 4px solid #4caf50;

      p {
        margin: 0;
        color: #2e7d32;
        font-size: 13px;
      }
    }
  }

  .sort-container {
    .sort-list {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .sort-item {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 16px;
      background: #f8f9fa;
      border: 2px solid #e9ecef;
      border-radius: 8px;
      cursor: move;
      transition: all 0.3s ease;

      &:hover {
        background: #e9ecef;
        border-color: #667eea;
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }

      .drag-handle {
        color: #6c757d;
        font-size: 18px;
        cursor: grab;

        &:active {
          cursor: grabbing;
        }
      }

      .item-content {
        flex: 1;
        display: flex;
        align-items: center;
        gap: 12px;

        .item-image {
          width: 180px;
          height: 80px;
          object-fit: contain;
          border-radius: 6px;
        }

        .item-name {
          font-weight: 500;
          color: #2c3e50;
        }
      }

      .item-order {
        width: 30px;
        height: 30px;
        background: linear-gradient(90deg, #44d4a8 33%, #28c68e 100%);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        font-size: 12px;
      }
    }
  }

  .message {
    position: fixed;
    top: 20px;
    right: 20px;
    padding: 12px 24px;
    border-radius: 6px;
    color: white;
    font-weight: 500;
    z-index: 1000;
    animation: slideIn 0.3s ease;

    &.success {
      background: #4caf50;
    }

    &.error {
      background: #f44336;
    }
  }
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>
